# -*- coding: utf-8 -*-


"""
Game loading screen.

Button "Load" -> screen "Players order".

I need:
    - Nothing
I will edit:
    - All gamestate
"""

import urllib2

from kivy.app import App
from kivy.properties import StringProperty
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

from model.gamestate import *
from ui.hat_widget import HatWidget
from model.json_loader import JsonLoader
import constants


class LoadGameScreen(HatWidget):
    HOST = constants.HOST
    # HOST is used in .kv file
    game_id = StringProperty()
    pin_code = StringProperty()
    """ Drawing screen which will be used for loading a game
    """

    def __init__(self, game_state, presenter, **kwargs):
        super(LoadGameScreen, self).__init__(**kwargs)
        self.game_state = game_state
        self.presenter = presenter
        self.game_id = u''
        self.pin_code = u''
        self.input_id.select_all()

    def update_id(self, value):
        self.game_id = value

        if self.game_id.isdigit() and self.pin_code.isdigit():
            self.load_button.enabled = True
        else:
            self.load_button.enabled = False

    def update_pin(self, value):
        self.pin_code = value

        if self.game_id.isdigit() and self.pin_code.isdigit():
            self.load_button.enabled = True
        else:
            self.load_button.enabled = False

    def on_load_pressed(self):
        """ Called when button "Load" is pressed". Load gamestate by id.

            loads json with gamestate from
            <HOST>/game_template_json?game_id=<game_id>&pin=<pin_code>
            changes phase to PLAYERS_ORDER
        """
        loader = JsonLoader()
        try:
            self.presenter.\
                game_state = \
                loader.load_from_url(self.HOST +
                                     '/game_template_json?game_id='
                                     + self.game_id +
                                     '&pin=' + self.pin_code)
        except urllib2.HTTPError as msg:
            if msg.code == 404:
                error_text = _('Game not found.\nCheck you game-id')
            elif msg.code == 403:
                error_text = _('Incorrect pin.')
            else:
                error_text = _('Network error')
            self.open_ok_popup(_('Error'), error_text)
            return
        except urllib2.URLError as msg:
            self.open_ok_popup(_('Error'), _('Network error'))
            return

        self.game_state.pin_code = pin_code
        self.presenter.change_phase(Phase.PLAYERS_ORDER)

    def go_back(self):
        self.presenter.change_phase(Phase.WELCOME)
